package com.asion.qkan.ui.activity;

import android.app.Activity;
import android.app.Service;
import android.content.ComponentName;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.TextView;

import com.asion.qkan.R;
import com.asion.qkan.db.Music;
import com.asion.qkan.db.MusicDao;
import com.asion.qkan.entry.MusicBean;
import com.asion.qkan.jiguangtuisong.ExampleApplication;
import com.asion.qkan.service.MusicPlayerService;
import com.asion.qkan.service.SeekBarChangeRecevice;
import com.asion.qkan.ui.util.BlurImage;
import com.asion.qkan.ui.util.Constant;
import com.asion.qkan.ui.util.MusicPlayDiscView;

import org.greenrobot.greendao.query.Query;

import java.io.IOException;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import rx.Observable;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

public class PlayActivity extends AppCompatActivity implements SeekBar.OnSeekBarChangeListener, AdapterView.OnItemClickListener {

    @BindView(R.id.rela)
    RelativeLayout rela;
    @BindView(R.id.list)
    ListView playlist;
    @BindView(R.id.tv_play_time)
    TextView tvPlayTime;
    @BindView(R.id.seekBar)
    SeekBar seekBar;
    @BindView(R.id.play_alltime)
    TextView playAlltime;
    @BindView(R.id.moshi)
    ImageView moshi;
    @BindView(R.id.btn_prev)
    ImageView btnPrev;
    @BindView(R.id.btn_play)
    ImageView btnPlay;
    @BindView(R.id.btn_next)
    ImageView btnNext;
    @BindView(R.id.leibiao)
    ImageView leibiao;
    @BindView(R.id.linear)
    LinearLayout linear;
    @BindView(R.id.back)
    ImageView back;
    @BindView(R.id.title)
    TextView title;
    @BindView(R.id.name)
    TextView playname;
    private MusicPlayDiscView musicPlayDiscView;
    private List<Music> musicsList = new ArrayList<>();

    private ServiceConnection serviceConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            myBinder = ((MusicPlayerService.MyBinder) service);
            musicsList=myBinder.getMusicList();
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
        }
    };

    private String mp3Url;
    private String picUrl;

    public static void startAction(Activity activity, Bundle bundle) {
        Intent intent = new Intent(activity, PlayActivity.class);
        intent.putExtra("bundle", bundle);
        activity.startActivity(intent);
        activity.overridePendingTransition(R.anim.fade_in,
                R.anim.fade_out);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            Window window = getWindow();
            window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION);
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            window.setStatusBarColor(Color.TRANSPARENT);
        }
        setContentView(R.layout.activity_play);
        ButterKnife.bind(this);

        Intent intent = new Intent(this, MusicPlayerService.class);
        bindService(intent, serviceConnection, Service.BIND_AUTO_CREATE);
        startService(intent);

        IntentFilter intentFilter = new IntentFilter("changeseek");
        recevier = new SeekBarChangeRecevice(handler);//更新进度条的广播
        registerReceiver(recevier, intentFilter);

        musicPlayDiscView = new MusicPlayDiscView(this);
        rela.addView(musicPlayDiscView);

        getBundleDatas();
        setPlayListener();
        setLieBiaoListener();
        setMoshiListener();

        back.setOnClickListener(v->finish());

        btnPrev.setOnClickListener(v -> {
            handler.removeMessages(101);
            seekBar.setProgress(0);
            myBinder.pre();
//            initPlay();
        });
        btnNext.setOnClickListener(v -> {
            handler.removeMessages(101);
            seekBar.setProgress(0);
            myBinder.next();
//            initPlay();
        });
    }

    private void initPlay() {
        String nexttitle = myBinder.getNexttitle();
        Observable<Music> map = Observable.just(nexttitle).observeOn(Schedulers.newThread())
                .map(s -> {
                    Query<Music> build = ExampleApplication.getMusicDao().queryBuilder().where(MusicDao.Properties.Title.eq(s)).build();
                    return build.list().get(0);
                });
        map.map(music -> music.getTitle()).observeOn(AndroidSchedulers.mainThread()).subscribe(title::setText);
        map.map(music -> music.getName()).observeOn(AndroidSchedulers.mainThread()).subscribe(playname::setText);
        map.map(music -> music.getPicurl()).observeOn(AndroidSchedulers.mainThread()).subscribe(s -> setBackgroundByNet(s));
    }


    private int count = 1;

    private void setMoshiListener() {
        moshi.setOnClickListener(v -> {
            switch (count % 3) {
                case 2:
                    moshi.setImageResource(R.drawable.a_q);
                    myBinder.setType(1);
                    break;
                case 1:
                    moshi.setImageResource(R.drawable.a_z);
                    myBinder.setType(0);
                    break;
                case 0:
                    moshi.setImageResource(R.drawable.aa_);
                    myBinder.setType(2);
                    break;
            }
            count++;
        });
    }

    private List<String> stringList = new ArrayList<>();
    private boolean isShow;

    private void setLieBiaoListener() {
        leibiao.setOnClickListener(v -> {
            stringList.clear();
            for (Music musics : musicsList) {
                stringList.add(musics.getTitle());
            }
            ArrayAdapter<String> adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_activated_1, stringList);
            playlist.setAdapter(adapter);
            if (isShow) {
                rela.setVisibility(View.VISIBLE);
                playlist.setVisibility(View.GONE);
            } else {
                rela.setVisibility(View.GONE);
                playlist.setVisibility(View.VISIBLE);
            }
            isShow = !isShow;

            playlist.setOnItemClickListener(this);
        });
    }


    private boolean flag;

    private void setPlayListener() {
        btnPlay.setOnClickListener(v -> {
            if (flag) {
                btnPlay.setImageResource(R.drawable.a9i);
                Constant.CurrentState = Constant.Play;
                myBinder.setMusic(mp3Url);
            } else {
                btnPlay.setImageResource(R.drawable.a9k);
                Constant.CurrentState = Constant.Pause;
                handler.removeMessages(101);
                myBinder.pause();
            }
            flag = !flag;
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
        setBackgroundByNet(picUrl);
    }

    private void getBundleDatas() {
        Bundle bundle = getIntent().getBundleExtra("bundle");
        MusicBean.ResultBean.TracksBean trackbean = (MusicBean.ResultBean.TracksBean) bundle.getSerializable("trackbean");
        if (trackbean != null) {
            String name = trackbean.getName();
            title.setText(name);
            playname.setText(trackbean.getAlbum().getArtists().get(0).getName());
            seekBar.setMax(trackbean.getDuration());
            playAlltime.setText(progresstime(trackbean.getDuration()));
            seekBar.setOnSeekBarChangeListener(this);
            mp3Url = trackbean.getMp3Url();
            picUrl = trackbean.getAlbum().getPicUrl();
        }
    }

    private void setBackgroundByNet(String pic) {
        Observable<Bitmap> map = Observable.just(pic).observeOn(Schedulers.io())
                .map(s -> {
                    try {
                        return new URL(s).openConnection().getInputStream();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    return null;
                }).map(BitmapFactory::decodeStream);
        map.observeOn(Schedulers.io()).map(BlurImage::createBlurBitmap)
                .map(BitmapDrawable::new)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(linear::setBackground);
        map.observeOn(AndroidSchedulers.mainThread()).subscribe(musicPlayDiscView::setBitmapImage);
    }

    @Override
    public void onBackPressed() {
        finish();
    }

    private String progresstime(int progress) {
        Date date = new Date(progress);
        SimpleDateFormat format = new SimpleDateFormat("mm:ss");
        return format.format(date);
    }

    private MusicPlayerService.MyBinder myBinder;
    private SeekBarChangeRecevice recevier;

    @Override
    public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {

    }

    @Override
    public void onStartTrackingTouch(SeekBar seekBar) {

    }

    @Override
    public void onStopTrackingTouch(SeekBar seekBar) {
        int progress = seekBar.getProgress();
        tvPlayTime.setText(progresstime(progress));
        myBinder.setProgress(progress);
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        Music music = musicsList.get(position);
        title.setText(music.getTitle());
        playname.setText(music.getName());
        setBackgroundByNet(music.getPicurl());
        myBinder.setPosition(position);//播放指定位置的歌曲
        handler.removeMessages(101);//去掉进度自动更新
        seekBar.setProgress(0);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unbindService(serviceConnection);
        unregisterReceiver(recevier);
    }

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 100://播放,更新进度条
                    sendEmptyMessage(101);
                    break;
                case 101:
                    seekBar.setProgress(seekBar.getProgress() + 1000);
                    tvPlayTime.setText(progresstime(seekBar.getProgress()));
                    sendEmptyMessageDelayed(101,1000);
                    break;
                case 105://代表播放完成
                    seekBar.setProgress(0);
                    tvPlayTime.setText(progresstime(0));
                    break;
            }

        }
    };
}
